package com.itc.bi.easyExcelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: itc-airport-cloud
 * @BelongsPackage: com.itc.bi.easyExcelListener
 * @Author: hecaiy
 * @CreateTime: 2024-09-17  18:18
 * @Description: TODO
 * @Version: 1.0
 */
@Data
public class LimitExcelReadListener extends AnalysisEventListener<Map<Integer, String>> {
    // 定义变量，分别表示限制列数和行数
    private Integer limitColSize;
    private Integer limitRowSize;
    // 定义变量，存储表头信息和表数据
    private List<Map<Integer, String>> headList = new ArrayList<>();
    private List<Map<Integer, String>> dataList = new ArrayList<>();
    // 构造函数
    LimitExcelReadListener() {

    }
    // 带参构造函数，直接赋值限制行列
    LimitExcelReadListener(Integer limitColSize, Integer limitRowSize) {
        this.limitColSize = limitColSize;
        this.limitRowSize = limitRowSize;
    }

    /**
     * 工具方法，根据传入的列限制来保留数据，也就是只取前几个Key，如果有需求，可以自己添加KeySet排序之后再取，我这里没这个需求
     * @param oldMap 未限制列前的Map
     * @return 限制列后的Map
     */
    private Map<Integer, String> getLimitColMap(Map<Integer, String> oldMap) {
        Integer size = oldMap.keySet().size();
        Map<Integer, String> newMap = new HashMap<>();
        for (int i = 0; i < (size >= this.limitColSize ? this.limitColSize : size); i++) {
            newMap.put(i, oldMap.get(i));
        }
        return newMap;
    }

    @Override
    public void invoke(Map<Integer, String> integerStringMap, AnalysisContext analysisContext) {
        // 获取限制列之后的Map，并存入dataList
        Map<Integer, String> newMap = this.getLimitColMap(integerStringMap);
        dataList.add(newMap);

        // 判断行数已达到限制行数，抛出ExcelAnalysisException
        if (dataList.size() >= this.limitRowSize) {
            throw new ExcelAnalysisException(this.limitRowSize + "行" + this.limitColSize + "列读取完成");
        }
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        // 获取限制列之后的表头Map，并存入headList
        Map<Integer, String> newMap = this.getLimitColMap(headMap);
        headList.add(newMap);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }
}